package com.iOS.util;

import java.io.File;
import java.io.InputStream;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
*@Author:WenTao
*@Description:文件存储工具类
*@Date:14:46 2018/9/20
*/
public class FileUtil {
    private static final Random r = new Random();
    private static final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyyMMddHHmmss");
    /*获取文件流，返回存储路径*/
    public static String ManageFile(InputStream fileInputStream, String fileName, String targetAddr){
        /*获取文件拓展名后缀*/
        String lastname = getFileExtension(fileName);

        /*获取保存到服务器后的文件名*/
        String realFileName = getRandomFileName();

         /*创建目录*/
        makeDirPath(targetAddr);

        /*绝对路径*/
        String relativeAddr = targetAddr + realFileName + lastname;

        /*创建要存储的文件*/
        File file = new File(relativeAddr);

        /*FMinputStream写入文件*/
        try {
            java.nio.file.Files.copy(fileInputStream,file.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }catch (Exception e){
            e.printStackTrace();
        }
        return relativeAddr;
    }

    /*获取输入文件流拓展名后缀*/
    private static String getFileExtension(String fileName){
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /*生成新文件名**/
    private static String getRandomFileName(){
        /*当前修改时间加四位随机数*/
        int rannum = r.nextInt(8999) + 1000;
        String nowTimeStr = sDateFormate.format(new Date());
        return nowTimeStr + rannum;
    }

    /*创建目标路径所涉及的目录*/
    private static void makeDirPath(String targetAddr){
        String realFileParentPath =targetAddr;
        File dirPath = new File(realFileParentPath);
        if (!dirPath.exists()){
            dirPath.mkdirs();
        }
    }

    /*文件删除*/
    private static void deleteFile(String targetAddr){
        try {
            java.io.File delFile = new java.io.File(targetAddr);
            delFile.delete();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
